package com.kevin.swing;

import java.awt.Color;

import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class TextPaneKevin extends JTextPane {

    private String commonstyle = "showStyle";
    private String highlightStyle = "highlightStyle";
    private StyledDocument styledDoc = new DefaultStyledDocument();

    public TextPaneKevin(StyledDocument styledDoc) {
        super(styledDoc);
        this.styledDoc = styledDoc;
        // Content
        createStyle("Style01", 15, 0, 1, 0, Color.RED, "宋体");
        createStyle("Style02", 35, 1, 1, 1, Color.GREEN, "华文琥珀");
        createStyle("Style03", 25, 1, 0, 0, Color.BLUE, "隶书");
        createStyle("Style07", 18, 1, 1, 0, Color.RED, "华文彩云");

        createStyle(commonstyle, 12, 0, 0, 0, Color.BLACK, "宋体");
        createStyle(highlightStyle, 12, 0, 0, 0, Color.RED, "宋体");
    }

    public TextPaneKevin() {
        super();
    }

    private static final long serialVersionUID = 1000123L;

    public void insertHighLightDoc(String content) {
        insertDoc(content, highlightStyle);
    }

    public void insertDoc(String content) {
        insertDoc(content, commonstyle);
    }

    public void insertDoc(String content, String currentStyle) {
        try {
            styledDoc.insertString(styledDoc.getLength(), content, styledDoc.getStyle(currentStyle));
        } catch (BadLocationException e) {
            System.err.println("BadLocationException: " + e);
        }
    }

    public void createStyle(String style, int size, int bold, int italic, int underline, Color color, String fontName) {
        Style sys = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
        try {
            styledDoc.removeStyle(style);
        } catch (Exception e) {
        } // 先删除这种Style,假使他存在

        Style s = styledDoc.addStyle(style, sys); // 加入
        StyleConstants.setFontSize(s, size); // 大小
        StyleConstants.setBold(s, (bold == 1) ? true : false); // 粗体
        StyleConstants.setItalic(s, (italic == 1) ? true : false); // 斜体
        StyleConstants.setUnderline(s, (underline == 1) ? true : false); // 下划线
        StyleConstants.setForeground(s, color); // 颜色
        StyleConstants.setFontFamily(s, fontName); // 字体
    }
}
